import { sendCode, SendCodeType } from '@/util/UserUtil'
import Validator from '@/util/Validator'
import { Button, Form, useFormApi } from '@douyinfe/semi-ui'
import { Dispatch, MutableRefObject, SetStateAction } from 'react'

export interface ICUserEmailCode {
  setCodeText: Dispatch<SetStateAction<string>>
  timer: MutableRefObject<NodeJS.Timer | undefined>
  clearTimer: () => void
  codeText: string
  loading: boolean
  sendCodeType: SendCodeType
  noLabel?: boolean
}

export default function CEmailOrPhoneCode(props: ICUserEmailCode) {
  const formApi = useFormApi()

  let fieldName = ''
  if (
    props.sendCodeType === 2 ||
    props.sendCodeType === 5 ||
    props.sendCodeType === 6 ||
    props.sendCodeType === 8
  ) {
    fieldName = 'phone'
  } else if (props.sendCodeType === 3) {
    fieldName = 'emailOrPhone'
  } else if (props.sendCodeType === 4 || props.sendCodeType === 7) {
    fieldName = 'email'
  }

  return (
    <div className="flex ai-e">
      <Form.Input
        label={{ text: '验证码', required: true }}
        field="code"
        placeholder={props.noLabel ? '请输入验证码' : ''}
        noLabel={props.noLabel}
        validate={Validator['numberCodeValidate']}
        noErrorMessage
        maxLength={6}
      />
      <Button
        block
        className="m-l-10 m-b-12 flex1"
        onClick={() => {
          formApi.validate([fieldName]).then(() => {
            sendCode(
              formApi.getValue(fieldName),
              props.setCodeText,
              props.timer,
              props.clearTimer,
              props.sendCodeType
            )
          })
        }}
        disabled={props.codeText !== '获取验证码' || props.loading}
      >
        {props.codeText}
      </Button>
    </div>
  )
}
